package com.shiro.config;

import com.shiro.pojo.User;
import com.shiro.service.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.mgt.AuthorizingSecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 定义UserRealm
 * @ClassName: 定义UserRealm
 * @Description:
 * @Author: Administrator
 * @Date: 2021/3/22 0022 下午 15:12
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserServiceImpl UserService;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权 ===》 doGetAuthorizationInfo");

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal(); // 获取对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        // 设置当前用户权限
        info.addStringPermission(user.getPerms());

        return info;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证 ====》 doGetAuthenticationInfo");

        // 获取当前用户信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = UserService.queryUserByName(token.getUsername());

        if(user == null){
            return null;
        }
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("loginUser",user);

        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}
